package cn.xerllent.wxtp.handler;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import cn.xerllent.wxtp.entity.Dksb;
import cn.xerllent.wxtp.service.DksbService;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.bean.message.WxCpTpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;

/**
 * 审批状态变化通知回调
 *
 */
@Component
public class OpenApprovalChangetHandler extends AbstractHandler {

	@Autowired
	private DksbService dksbService;

	@Override
	public WxCpXmlOutMessage handle(WxCpTpXmlMessage wxMessage, Map<String, Object> context,
			WxCpTpService wxCpTpService, WxSessionManager sessionManager) {
		String suiteId = wxCpTpService.getWxCpTpConfigStorage().getSuiteId();
		String thirdNo = wxMessage.getApprovalInfo().getThirdNo(); // 流程id
		String corpId = wxMessage.getToUserName(); // 授权企业id
		String auditUserId = wxMessage.getApprovalInfo().getApplyUserId(); // 审批人id
		String auditNotes="";
		try {
			auditNotes = wxMessage.getApprovalInfo().getApprovalNodes().iterator().next().getItems().iterator().next().getItemSpeech();
		} catch (Exception e) {
		}
		Integer status = wxMessage.getApprovalInfo().getOpenSpStatus();
		Long applytime = wxMessage.getApprovalInfo().getApplyTime();

		// 区分业务
		if (suiteId.equals("wwa96d2ab2354ee862")) { // 代课申报
			Dksb dksb = dksbService.getOne(new LambdaQueryWrapper<Dksb>().eq(Dksb::getCorpId, corpId).eq(Dksb::getThirdNo, thirdNo));
			if(dksb!=null) {
				dksb.setStatus(status)
				.setAuditUserid(auditUserId)
				.setAuditNotes(auditNotes)
				.setAudittime(LocalDateTime.ofEpochSecond(applytime, 0, ZoneOffset.UTC));
				dksbService.saveOrUpdate(dksb);
			}
		}

		return null;
	}

}
